import { defineConfig, loadEnv } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
import AutoImport from 'unplugin-auto-import/vite';
import path from 'path';
import fs from 'fs';

export default defineConfig((configEnv: any): any => {
  const viteEnv = loadEnv(configEnv.mode, process.cwd()) as unknown as any;
  return {
		css: {
			preprocessorOptions: {
				scss: {
        	additionalData: `$serverImg: \"${viteEnv.VITE_serverImg}\";`
				},
			},
		},
    plugins: [ 
			uni(), 
			AutoImport({
				include: [
					/\.[tj]sx?$/,
					/\.vue$/,
					/\.vue\?vue/,
				],
				imports: [
					'vue',
					'pinia'
				],
				dts: 'src/types/auto-imports.d.ts'
			}),
			{
				name: 'replaceAppCssPlugin',
				apply: 'build',
				enforce: 'post',
				writeBundle() {
					const filePath = path.join(__dirname, 'dist/build/mp-weixin/app.wxss');
					try {
						let fileContent = fs.readFileSync(filePath, 'utf8')
						fileContent = fileContent.replaceAll('shadow-preload .1s', 'shadowpreload .1s');
						fs.writeFileSync(filePath, fileContent)
					} catch(e) {}
				}
			}
		],
    build: {
			base: './',
      reportCompressedSize: false,
      sourcemap: false,
      target: 'es2015',
      commonjsOptions: {
        ignoreTryCatch: false
      },
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: configEnv.mode == 'production' ? ['log', 'info'] : false,
          drop_debugger: true,
        },
      },
    }
  }
})